#include "media_sys.h"

bool Album(MEDIA_POI mp) //相册总接口
{

    P_AI p_ai = Album_Init(mp);
    if(p_ai == (P_AI)-1)
    {
        printf("相册模块初始化失败！\n");
        return false;
    }


    if(Album_Touch_Ctrl(mp,p_ai) == false)
    {
        printf("相册触摸屏控制失败！\n");
        return false;
    }

    return true;
}


P_AI    Album_Init(MEDIA_POI mp) //被相册总接口Album调用
{
    Lcd_Clean(mp,0x00ffffff);

    //申请相册结构体堆空间
    P_AI p_ai = (P_AI)malloc(sizeof(AI));
    if(p_ai == (P_AI)NULL)
    {
        perror("malloc ...");
        return (P_AI)-1;
    }

    memset(p_ai,0,sizeof(AI));


    //创建图片链表头节点
    if((p_ai->bmp_list_head = Create_Bmp_Node()) == (BMP_LINK)-1)//创建图片链表头结点
    {
        printf("创建图片链表头结点失败！\n");
        return (P_AI)-1;
    }

    //相册bmp检索
    if(Bmp_File_Search(p_ai,mp) == false)
    {
        printf("bmp图片检索失败！\n");
        return (P_AI)-1;
    }

    //检索完成界面
    if(Show_Page_Thumbnail(mp,p_ai,1) == false)
    {
        printf("显示缩略图失败！\n");
        return (P_AI)-1;
    }

    return p_ai;
}


BMP_LINK      Create_Bmp_Node()  //头结点
{
    BMP_LINK new_node = (BMP_LINK)malloc(sizeof(BMP_NODE));
    if(new_node == (BMP_LINK)NULL)
    {
        perror("malloc bmp node ...");
        return (BMP_LINK)-1;
    }

    memset(new_node,0,sizeof(BMP_NODE));

    new_node->next = new_node;
    new_node->prev = new_node;

    return new_node;
}


bool Bmp_File_Search(P_AI p_ai,MEDIA_POI mp) //bmp图片的检索
{
    //打开存放相册图片的目录
    DIR * dp = opendir(DEFAULT_SEARCH_BMP_PATH);
    if(dp == (DIR *)NULL)
    {
        perror("opendir ...");
        return false;
    }

    //死循环读取文件名字，
    while(1)
    {
        struct dirent * eq = readdir(dp);
        if(eq == (struct dirent * )NULL)
        {
            printf("-----\n");
            break;
        }

        //忽略.和..
        if(eq->d_name[0] == '.') continue;

        //如果是.bmp,倒数第四个字符的下标 = strlen(eq->d_name)-4  -1 p -2 m -3 b -4 .
        
        if((eq->d_type == DT_REG) && (strcmp(&eq->d_name[strlen(eq->d_name)-4],PIC_FILE_TYPE) == 0))
        {   
            
            //创建一个节点
            BMP_LINK bmp_node = Create_Bmp_Node();
            if(bmp_node == (BMP_LINK)-1)
            {
                printf("创建图片结点失败！\n");
                return false;
            }

            //保存他的文件路径到节点的bmp_path，
            sprintf(bmp_node->bmp_path,"%s/%s",DEFAULT_SEARCH_BMP_PATH,eq->d_name);

            //头插到链表中
            if(Add_Bmp_Node(p_ai,bmp_node) == false)
            {
                printf("添加图片链表节点失败！\n");
                return false;
            }

            p_ai->photo_sum++;//图片数量+1

        }
    }

    //跳出while之后，p_ai->photo_sum就是图片的总数，通过图片的总数去求页数
    if(p_ai->photo_sum % 9 == 0)
    {
        p_ai->photo_page_sum = p_ai->photo_sum / 9;
    }
    else
    {
        p_ai->photo_page_sum = p_ai->photo_sum / 9 + 1;
    }

    printf("检索相册图片成功，个数:%d张，页数:%d页，文件如下：\n",p_ai->photo_sum,p_ai->photo_page_sum);

    //关闭目录
    if(closedir(dp) == -1)
    {
        perror("closedir ...");
        return false;
    }

    //检索进度条
    Show_Ui(mp,"/ui/Bmp_File_Search_Ui.bmp");

    for(int n = 103;n<698;n++)
    {
        for (int y = 303; y < 349; y++)
        {
            int index = y * mp->lcd_w + n;
            *(mp->mmap_start_poi + index) = 0x000000;
        }
        usleep(4000);
    }

    Lcd_Clean(mp,0x00ffffff);

    int tmp_x=10;
    int tmp_y=10;
    BMP_LINK tmp_node = p_ai->bmp_list_head;
    while(1)
    {
        tmp_node = tmp_node->next;
        if (tmp_node == p_ai->bmp_list_head)
        {
            break;
        }
        Sentence_Show(tmp_node->bmp_path,mp,tmp_x,tmp_y);
        tmp_y += 25;
    }
    sleep(3);

    return true;
}


bool Add_Bmp_Node(P_AI p_ai,BMP_LINK new_node)  //头插法添加图片链表节点
{
    if(p_ai == (P_AI)NULL || p_ai->bmp_list_head == (BMP_LINK)NULL)
    {
        printf("地址异常！\n");
        return false;
    }

    new_node->prev                  = p_ai->bmp_list_head->prev;
    p_ai->bmp_list_head->prev->next = new_node;

    new_node->next = p_ai->bmp_list_head;

    p_ai->bmp_list_head->prev = new_node;

    return true;
}


bool Show_Page_Thumbnail(MEDIA_POI mp,P_AI p_ai,int page_num) //指定显示某一页的缩略图   200*120
{
    //如果page  等于1  不用循环
    //如果page 等于 2 也就是第10张开始后面的9张，写一个for循环9次
    //如果page 等于 3 写一个for循环18次


    //获取指定页数在链表的中第一张缩略图的图片节点
    int loop_num = (page_num-1) * 9;

    BMP_LINK obj_bmp_node = p_ai->bmp_list_head->next;

    for(int index=0; index < loop_num; index++)
    {
        obj_bmp_node = obj_bmp_node->next;
    }

    int bmp_x = 10;
    int bmp_y = 20;

    int ascii_x = 10;
    int ascii_y = 140;
    //循环9 次 显示9张缩略图 ，如果当前页数的图片数量不满 9 张 提前 跳出循环
    Show_Ui(mp,"/ui/alb_ui.bmp");
    for(int index = 0; index < 9; index++,obj_bmp_node=obj_bmp_node->next)
    {
        if(obj_bmp_node == p_ai->bmp_list_head) break;

        //显示当前节点对应的图片的缩略图
        
        if(Show_One_Thumbnail(mp,obj_bmp_node->bmp_path,4,bmp_x,bmp_y) == false)
        {
            printf("显示缩略图失败！\n");
            return false;
        }

        if(Sentence_Show(&obj_bmp_node->bmp_path[5],mp,ascii_x,ascii_y) == false)
        {
            printf("显示字体失败！\n");
            return false;
        }

        bmp_x += 220;
        ascii_x += 220;

        if(bmp_x > 481)
        {
            bmp_x = 10;
            bmp_y+=150;

            ascii_x = 10;
            ascii_y+=150;
        }
    }
    return true;
}


bool Show_One_Thumbnail(MEDIA_POI mp,const char * bmp_path, int zoomout,int bmp_x,int bmp_y)
{

    int * tmp_mmap_p = mp->mmap_start_poi + mp->lcd_w * bmp_y + bmp_x;
    //打开图片
    int bmp = open(bmp_path,O_RDONLY);
    if(bmp == -1)
    {
        perror("bmp ...");
        return false;
    }


    //获取图片w和h
    int bmp_w,bmp_h;
    lseek(bmp,18,SEEK_SET);
    if(read(bmp,&bmp_w,sizeof(int)) == -1)
    {
        perror("Read w ...");
        return false;
    }

    if(read(bmp,&bmp_h,sizeof(int)) == -1)
    {
        perror("Read h ...");
        return false;
    }


    //计算skip
    int skip = 0;
    if(bmp_w*3%4 != 0)
    {
        skip = 4 - (bmp_w*3%4);
    }

    //定义数组
    int bmp_size = bmp_w * bmp_h * 3 + bmp_h * skip;
    //printf("即将缩小%d倍显示宽：%d-高：%d的%s图片--- %d\n",zoomout,bmp_w,bmp_h,bmp_path,skip);

    char rgb[bmp_size];

    //read读取图片像素点 + 补齐字节数
    lseek(bmp,54,SEEK_SET);

    if(read(bmp,rgb,bmp_size) == -1)
    {
        perror("read ...");
        return false;
    }


    for(int y=0,n=0; y<bmp_h /zoomout; y++) 
    {

        for(int x=0; x<bmp_w / zoomout; x++,n+=(3*zoomout))
        {   
            
            *(tmp_mmap_p + 800*(bmp_h / zoomout-1-y)+x) = rgb[n] <<0 | rgb[n+1] << 8 | rgb[n+2]<<16;

        }
        
        //跳补数
        n += skip;

        //需要跳剩余的像素点字节数
        n+= (bmp_w % zoomout) * 3;


        //跳行数 跳 zoomout-1行数 字节数
        n+=bmp_w * (zoomout-1) * 3 + skip *(zoomout-1);

    }


    if(close(bmp) == -1)
    {
        perror("close ...");
        return false;
    }

    return true;
}


bool Show_Original_Drawing(int page_num,int n,MEDIA_POI mp,P_AI p_ai)//显示原图 n是图片位置
{
    int loop_num = (page_num-1) * 9 + n;

    BMP_LINK obj_bmp_node = p_ai->bmp_list_head->next;

    for(int index=0; index < loop_num; index++)
    {
        obj_bmp_node = obj_bmp_node->next;
    }

    if(loop_num < p_ai->photo_sum) 
    {
        Lcd_Clean(mp,0x00ffffff);
        if (Show_One_Thumbnail(mp,obj_bmp_node->bmp_path,1,0,0) == false)
        {
            printf("显示原图失败\n");
            return false;
        }
    }
                    
    while(loop_num < p_ai->photo_sum)
    {
        if(Get_Touch_Xy(mp,0) == false)
        {
            printf("读取触摸屏坐标失败！\n");
            return false;
        }

        if(mp->touch_x > 683 && mp->touch_x < 773 && mp->touch_y > 30 && mp->touch_y < 118)
        {
            if(Show_Page_Thumbnail(mp,p_ai,page_num) == false)
            {
                printf("显示缩略图失败！\n");
                return false;
            }
            break;
        }

        if(mp->touch_x > 0 && mp->touch_x < 300 && mp->touch_y > 240 && mp->touch_y < 480)
        {
            obj_bmp_node = obj_bmp_node->prev;
            if (obj_bmp_node == p_ai->bmp_list_head)
            {
                obj_bmp_node = obj_bmp_node->next;
                continue;
            }

            Lcd_Clean(mp,0x00ffffff);
            if (Show_One_Thumbnail(mp,obj_bmp_node->bmp_path,1,0,0) == false)
            {
                printf("显示上一张原图失败\n");
                return false;
            }
        }

        if(mp->touch_x > 500 && mp->touch_x < 800 && mp->touch_y > 240 && mp->touch_y < 480)
        {
            obj_bmp_node = obj_bmp_node->next;
            if (obj_bmp_node == p_ai->bmp_list_head)
            {
                obj_bmp_node = obj_bmp_node->prev;
                continue;
            }

            Lcd_Clean(mp,0x00ffffff);
            if (Show_One_Thumbnail(mp,obj_bmp_node->bmp_path,1,0,0) == false)
            {
                printf("显示下一张原图失败\n");
                return false;
            }
        }
    }
    return true;
}


bool Del_photo(int page_num,int n,MEDIA_POI mp,P_AI p_ai)//删除图片
{
    if(p_ai->photo_sum == 0)return true;
    int loop_num = (page_num-1) * 9 + n;

    BMP_LINK obj_bmp_node = p_ai->bmp_list_head->next;

    for(int index=0; index < loop_num; index++)
    {
        obj_bmp_node = obj_bmp_node->next;
    }
    obj_bmp_node->prev->next = obj_bmp_node->next;
    obj_bmp_node->next->prev = obj_bmp_node->prev;

    obj_bmp_node->next = NULL;
    obj_bmp_node->prev = NULL;

    free(obj_bmp_node);
    p_ai->photo_sum--;

    if(p_ai->photo_sum % 9 == 0)
    {
        p_ai->photo_page_sum = p_ai->photo_sum / 9;
    }
    else
    {
        p_ai->photo_page_sum = p_ai->photo_sum / 9 + 1;
    }

    printf("删除成功，个数:%d张，页数:%d页，文件如下：\n",p_ai->photo_sum,p_ai->photo_page_sum);
    return true;
}


bool Album_Touch_Ctrl(MEDIA_POI mp,P_AI p_ai)//相册界面触摸控制
{
    int page_num = 1;
    mp->touch_x = -1;
    mp->touch_y = -1;
    while(1)
    {
        //先获取点击的触摸坐标，再去判断坐标是哪个按钮的区间
        if(Get_Touch_Xy(mp,0) == false)
        {
            printf("读取触摸屏坐标失败！\n");
            return false;
        }

        if(mp->touch_x > 700 && mp->touch_x < 800 && mp->touch_y > 240 && mp->touch_y < 360 && page_num > 1) //上一页
        {
            printf("上一页 !\n");
            if(Show_Page_Thumbnail(mp,p_ai,--page_num) == false)
            {
                printf("显示缩略图失败！\n");
                return (P_AI)-1;
            }
        
        }
        else if(mp->touch_x > 700 && mp->touch_x < 800 && mp->touch_y > 360 && mp->touch_y < 480 && page_num < p_ai->photo_page_sum) //下一页
        {
            printf("下一页 !\n");
            if(Show_Page_Thumbnail(mp,p_ai,++page_num) == false)
            {
                printf("显示缩略图失败！\n");
                return (P_AI)-1;
            }
        }
        else if(mp->touch_x > 700 && mp->touch_x < 800 && mp->touch_y > 0 && mp->touch_y < 120) //退出返回主界面
        {
            //显示主界面
            time_up_down = 1;
            if(Show_Ui(mp,"/ui/main_ui.bmp") == false)
            {
                printf("显示主界面失败！\n");
                return false;
            }
            
            mp->touch_x = -1;
            mp->touch_y = -1;
            if (close_photo_link(p_ai) == false)
            {
                printf("摧毁失败！\n");
                return false;
            }
            free(p_ai);
            break;
        }else if(mp->touch_x > 700 && mp->touch_x < 800 && mp->touch_y > 120 && mp->touch_y < 240)//删除图片
        {
            
            int col = -1, row = -1;

            while (1)
            {
                if(Get_Touch_Xy(mp,0) == false)
                {
                    printf("读取触摸屏坐标失败！\n");
                    return false;
                }
                
                // 列坐标判断（横向间隔20像素，每列宽200）
                if (mp->touch_x > 10 && mp->touch_x < 210) col = 0;
                else if (mp->touch_x > 230 && mp->touch_x < 430) col = 1;
                else if (mp->touch_x > 450 && mp->touch_x < 650) col = 2;

                // 行坐标判断（纵向间隔20像素，每行高120）
                if (mp->touch_y > 10 && mp->touch_y < 130) row = 0;
                else if (mp->touch_y > 150 && mp->touch_y < 270) row = 1;
                else if (mp->touch_y > 290 && mp->touch_y < 410) row = 2;

                if (col != -1 && row != -1) 
                {
                    if(Del_photo(page_num,row * 3 + col,mp,p_ai) == true) break;
                }
            }

            if(Show_Page_Thumbnail(mp,p_ai,page_num) == false)
            {
                printf("显示缩略图失败！\n");
                return false;
            }
            
        }
        else
        {
            int col = -1, row = -1;

            // 列坐标判断（横向间隔20像素，每列宽200）
            if (mp->touch_x > 10 && mp->touch_x < 210) col = 0;
            else if (mp->touch_x > 230 && mp->touch_x < 430) col = 1;
            else if (mp->touch_x > 450 && mp->touch_x < 650) col = 2;

            // 行坐标判断（纵向间隔20像素，每行高120）
            if (mp->touch_y > 10 && mp->touch_y < 130) row = 0;
            else if (mp->touch_y > 150 && mp->touch_y < 270) row = 1;
            else if (mp->touch_y > 290 && mp->touch_y < 410) row = 2;

            if (col != -1 && row != -1) 
            {
                if(Show_Original_Drawing(page_num, row * 3 + col, mp, p_ai) == false)
                {
                    printf("显示原图失败！\n");
                    return false;
                }
            }
        }
    }


    return true;
}


bool close_photo_link(P_AI pa_i)//cuihui
{
    if (pa_i->bmp_list_head == (BMP_LINK)NULL)
    {
        printf("头结点异常\n");
        return false;
    }

    while(pa_i->bmp_list_head->next != pa_i->bmp_list_head)
    {
        BMP_LINK del_node = pa_i->bmp_list_head->next;

        del_node->prev->next = del_node->next;
        del_node->next->prev = del_node->prev;

        del_node->prev = NULL;
        del_node->next = NULL;

        free(del_node);
    }
    free(pa_i->bmp_list_head);
    printf("cgcgcgcgc\n");
    return true;
}
